#include "http_server.h"
#include "task.h"
#include "websocket.h"
#include <iostream>

class Room : public co_async::WebSocket {
public:
  Room(WebSocket &ws) : WebSocket(ws) {
    std::cout << "Room\n";
    on_message([this](co_async::WebSocketEndpoint &ep,
                      const std::string &msg) -> co_async::Task<bool> {
      std::cout << "on_message: " << msg << "\n";
      for (auto it : m_endpoints) {
        co_await it.second->send(msg);
      }
      co_return true;
    });
  }

  void on_message(co_async::WsHandler task) {
    WebSocket::on_message(
        [this, task](co_async::WebSocketEndpoint &ep,
                     const std::string &msg) -> co_async::Task<bool> {
          for (auto& it : m_endpoints) {
            co_await task(*it.second, msg);
          }
          co_return true;
        });
  }

private:
};

int main() {
  auto server = co_async::HttpServer("0.0.0.0", 8848);
  auto &room = static_cast<Room &>(server.update("/ws"));
  room.on_message([](co_async::WebSocketEndpoint &ep,
                     const std::string &msg) -> co_async::Task<bool> {
    std::cout << "on_message: " << msg << "\n";
    return ep.send(msg);
  });

  server.serve();
}